import React, { useEffect, useState } from 'react';
import { Layout, Menu, Button, Avatar, Dropdown, Modal } from 'antd';
import { Routes, Route, Link, useNavigate, Navigate, useLocation } from 'react-router-dom';
import { observer } from 'mobx-react-lite';
import classNames from 'classnames';
import { menuStore } from '../../store/public/menuStore.ts';
import { loginStore } from '../../store/public/loginStore.ts';
import styles from './MainLayout.module.css';
import themeStyles from './theme/theme.module.css';
import * as Icons from '@ant-design/icons';
import {
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  UserOutlined,
  LogoutOutlined,
  SettingOutlined,
  IdcardOutlined,
} from '@ant-design/icons';
import About from '../../pages/public/about/About.tsx';
import { routesMain } from '../../routes/lib';
import { systemName } from '../../globals/system.tsx';
import { getDownloadUrl } from '@/utils/fileUtil';
import bannerImg from '@/assets/banner.png';

const { Header, Content, Sider } = Layout;

/**
 * 前台布局
 */
const MainLayout: React.FC = observer(() => {
  const navigate = useNavigate();
  const location = useLocation();
  const [collapsed, setCollapsed] = useState(false);
  const [headerContent, setHeaderContent] = useState<React.ReactNode>(null);

  useEffect(() => {
    // 从 loginStore 中读取登录状态
    if (!loginStore.isAuthenticated) {
      navigate('/login');
    }
  }, [navigate]);

  // 登出功能
  const handleLogout = () => {
    loginStore.logout();
    navigate('/login');
  };

  // 系统信息弹窗
  const showSystemInfo = () => {
    Modal.info({
      title: '授权信息',
      width: 1000,
      content: <About />,
      okText: '确认',
      onOk() { },
    });
  };


  // 根据当前路径判断应该选中的菜单项
  const getSelectedKeys = () => {
    const path = location.pathname;
    const selected = menuStore.items.find(item =>
      path.includes(item.path.replace('/app', ''))
    );
    return selected ? [selected.key] : ['1'];
  };

  const admin = [
        {
          key: '1',
          icon: <UserOutlined />,
          label: '个人中心',
          onClick: () => navigate('/app/settings')
        },
        {
          key: 'sysinfo',
          icon: <IdcardOutlined />,
          label: '授权信息',
          onClick: showSystemInfo
        },
        {
          key: '2',
          icon: <SettingOutlined />,
          label: '前往后台设置',
          onClick: () => navigate('/engine')
        },
        {
          key: '3',
          icon: <LogoutOutlined />,
          label: '退出登录',
          onClick: handleLogout
        }
  ]

  const user = [
        {
          key: '1',
          icon: <UserOutlined />,
          label: '个人中心',
          onClick: () => navigate('/app/settings')
        },
        {
          key: 'sysinfo',
          icon: <IdcardOutlined />,
          label: '授权信息',
          onClick: showSystemInfo
        },
        {
          key: '3',
          icon: <LogoutOutlined />,
          label: '退出登录',
          onClick: handleLogout
        }
  ] 


  /**
   * 渲染头部
   * @returns 
   */
  const renderHeader = async () => {

    let username = '';
    let avatarUrl = '';
    let menu = user;
    if (window.HubUser) {
      username = window.HubUser?.username;
      if(window.HubUser?.avatar){
        avatarUrl = await getDownloadUrl(window.HubUser?.avatar);
      }
      if(window.HubUser?.roleId == '1' || window.HubUser?.roleId == '2'){
        menu = admin;
      }
    }
    return (
      <Header className={styles['statHub-layout-header']}>
        <div
          className={styles['statHub-layout-collapse-btn']}
          onClick={() => setCollapsed(!collapsed)}
        >
          {collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
        </div>
        <div className={styles['statHub-layout-user-container']}>
          <Dropdown menu={{
            items: menu
          }}>
            <div className={styles['statHub-layout-user-info']}>
              <Avatar icon={<UserOutlined />} src={avatarUrl}  />
              <span className={styles['statHub-layout-user-name']}>{username}</span>
            </div>
          </Dropdown>
        </div>
      </Header>
    )
  }

  useEffect(() => {
    const loadHeader = async () => {
      try {
        const header = await renderHeader();
        setHeaderContent(header);
      } catch (error) {
        console.error('加载头部内容失败:', error);
      }
    };
    
    loadHeader();
  }, []); // 依赖项根据实际情况添加

  return (
    <Layout className={styles['statHub-layout-container']}>
      <Sider
        width={220}
        collapsible
        collapsed={collapsed}
        onCollapse={(value) => setCollapsed(value)}
        className={classNames(
          styles['statHub-layout-sider'],
          themeStyles[`statHub-layout-sider-${menuStore.theme}`]
        )}
      >
        <div
          className={classNames(
            styles[`statHub-layout-logo`],
            { [styles[`statHub-layout-logo-collapsed`]]: collapsed },
            themeStyles[`statHub-layout-logo-${menuStore.theme}`]
          )}
        >
          {!collapsed && (<><img className="starHub-system-logo" src={bannerImg}/>{systemName}</>)}
        </div>
        <Menu
          theme={menuStore.theme}
          mode="inline"
          selectedKeys={getSelectedKeys()}
          className={classNames(
            styles['statHub-layout-menu'],
            themeStyles[`statHub-layout-menu-${menuStore.theme}`]
          )}
        >
          {menuStore.items.map(item => (
            <Menu.Item
              key={item.key}
              icon={item.icon && (Icons as any)[item.icon] ? React.createElement((Icons as any)[item.icon]) : null}
              className={`${styles['statHub-layout-menu-item']} ${location.pathname.includes(item.path.replace('/app', ''))
                ? styles['statHub-layout-menu-item-active']
                : ''
                }`}
            >
              <Link to={`/app${item.path}`}>{item.label}</Link>
            </Menu.Item>
          ))}
        </Menu>
      </Sider>
      <Layout className={`${styles['statHub-layout-main']} ${collapsed ? styles['statHub-layout-main-collapsed'] : ''}`}>
        {headerContent}
        <Content className={styles['statHub-layout-content']}>
          <div className={styles['statHub-layout-content-inner']}>
            <Routes>
              <Route index element={<Navigate to="/app/ai-assistant" replace />} />
              {routesMain.map(route => (
                <Route path={route.path} element={route.element} />
              ))}
            </Routes>
          </div>
        </Content>
      </Layout>
    </Layout>
  );
});

export default MainLayout; 